#include "gudb.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    printf("Testing database isolation functionality...\n");
    
    // Open database
    gudb* db = gudb_open("/tmp/gudb_data", GU_OPEN_CREATE, "admin", "admin");
    if (!db) {
        printf("FAIL: Could not open database\n");
        return 1;
    }
    
    printf("SUCCESS: Database opened\n");
    
    // Test 1: Start transaction with gudb database
    printf("\n=== Test 1: Start transaction with gudb database ===\n");
    gudb_txn* txn1 = gudb_begin(db, GU_TXN_RC, "gudb");
    if (!txn1) {
        printf("FAIL: Could not start transaction\n");
        gudb_close(db);
        return 1;
    }
    
    printf("SUCCESS: Transaction started with gudb database\n");
    printf("Current database: %s\n", gudb_txn_current_database(txn1));
    
    // Test 2: Execute USE command
    printf("\n=== Test 2: Execute USE isolation_test ===\n");
    result_t* result = NULL;
    if (gudb_exec(txn1, "USE isolation_test", NULL, &result) == GU_OK) {
        printf("SUCCESS: USE command executed\n");
        printf("Current database after USE: %s\n", gudb_txn_current_database(txn1));
        if (result) gudb_free_result(result);
    } else {
        printf("FAIL: USE command failed\n");
    }
    
    // Test 3: SHOW TABLES in same transaction
    printf("\n=== Test 3: SHOW TABLES in same transaction ===\n");
    if (gudb_exec(txn1, "SHOW TABLES", NULL, &result) == GU_OK) {
        printf("SUCCESS: SHOW TABLES executed\n");
        if (result && result->col_count > 0) {
            printf("Column header: %s\n", result->column_names[0]);
            printf("Tables found: %u\n", result->row_count);
        }
        if (result) gudb_free_result(result);
    } else {
        printf("FAIL: SHOW TABLES failed\n");
    }
    
    gudb_commit(txn1);
    
    // Test 4: Start new transaction with isolation_test
    printf("\n=== Test 4: Start new transaction with isolation_test ===\n");
    gudb_txn* txn2 = gudb_begin(db, GU_TXN_RC, "isolation_test");
    if (!txn2) {
        printf("FAIL: Could not start transaction\n");
        gudb_close(db);
        return 1;
    }
    
    printf("SUCCESS: Transaction started with isolation_test database\n");
    printf("Current database: %s\n", gudb_txn_current_database(txn2));
    
    // Test 5: SHOW TABLES in new transaction
    printf("\n=== Test 5: SHOW TABLES in new transaction ===\n");
    if (gudb_exec(txn2, "SHOW TABLES", NULL, &result) == GU_OK) {
        printf("SUCCESS: SHOW TABLES executed\n");
        if (result && result->col_count > 0) {
            printf("Column header: %s\n", result->column_names[0]);
            printf("Tables found: %u\n", result->row_count);
        }
        if (result) gudb_free_result(result);
    } else {
        printf("FAIL: SHOW TABLES failed\n");
    }
    
    gudb_commit(txn2);
    gudb_close(db);
    
    printf("\nTest completed.\n");
    return 0;
}